package com.jyxd.web.hiscz.service;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.jyxd.web.data.basic.NurseRecordForm;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.data.patient.PatientCriticalDescription;
import com.jyxd.web.hiscz.dto.BodyDto;
import com.jyxd.web.hiscz.dto.RequestBodyDto;
import com.jyxd.web.hiscz.dto.ResponseDto;
import com.jyxd.web.hiscz.dto.checkout_report.critical_obsInfo.CriticalObsInfo;
import com.jyxd.web.service.assessment.basic.NurseRecordFormService;
import com.jyxd.web.service.patient.PatientCriticalDescriptionService;
import com.jyxd.web.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.jyxd.web.hiscz.service.HisUtilService.*;
import static com.jyxd.web.util.ExecuteUtil.errorIfEmpty;
import static com.jyxd.web.util.UUIDUtil.getUUID;

@Service
public class CriticalDescriptionHisService {

    private static Logger logger = LoggerFactory.getLogger(HisDictionaryService.class);

    @Autowired
    private HisUtilService hisUtilService;

    @Autowired
    private PatientCriticalDescriptionService patientCriticalDescriptionService;

    @Autowired
    private NurseRecordFormService nurseRecordFormService;
    /**
     * 危急值
     *
     * @param request
     * @return
     */
    public ResponseDto requestDictionary(RequestBodyDto request) {
        try {
            logger.info("危急值接收患者数据为：" + JSON.toJSONString(request));

            isRequestEmpty(request);
            BodyDto body = request.getRequest().getBody();
            Patient patient = hisUtilService.getPatient(body);
            errorIfEmpty(patient, "患者不存在");
            String eventCode = getEventCode(body);
            System.out.println(eventCode);

            if (!StringUtils.equals(eventCode, "RAD0113") && !StringUtils.equals(eventCode, "RAD0114") &&
                    !StringUtils.equals(eventCode, "LAB0110") && !StringUtils.equals(eventCode, "LAB0111")) {
                logger.info("不为危机值接收事件，不做操作");
                return new ResponseDto(hisResponse(request.getRequest().getHead(), "100", "事件接收错误"));
            }
            Date dataTime = body.getEvent().getRecordDatetime();
            errorIfEmpty(body.getObservationResultList(), "危机值列表为空");
            body.getObservationResultList().forEach(observationResultDto -> {
                errorIfEmpty(observationResultDto.getCriticalObsInfo(), "危急值详情为空");
                setPatientCriticalDescription(observationResultDto.getCriticalObsInfo(), patient, dataTime);
            });
            return new ResponseDto(hisResponse(request.getRequest().getHead(), "100", "危急值数据处理成功"));
        } catch (Exception e) {
            logger.info("危急值数据处理出错：" + e.getMessage());
            return new ResponseDto(hisResponse(request.getRequest().getHead(), "100", e.getMessage()));
        }
    }

    /**
     * 查询重复危急值
     *
     * @param criticalObsInfo
     * @param patient
     * @return
     */
    private PatientCriticalDescription queryRepetition(CriticalObsInfo criticalObsInfo, Patient patient) {
        Map<String, Object> map = new HashMap<>();
        map.put("patientId", patient.getId());
        map.put("criticalDescription", criticalObsInfo.getCriticalDescription());
        return patientCriticalDescriptionService.queryDateByPatientIdAndCriticalDescription(map);
    }

    /**
     * 赋值新增患者危急值数据
     *
     * @param criticalObsInfo
     * @param patient
     * @param dataTime
     */
    private void setPatientCriticalDescription(CriticalObsInfo criticalObsInfo, Patient patient, Date dataTime) {
        PatientCriticalDescription patientCriticalDescription = queryRepetition(criticalObsInfo, patient);
        boolean isRepetition = true; // 是否存在重复危急值
        if (Objects.isNull(patientCriticalDescription)) {
            patientCriticalDescription = new PatientCriticalDescription();
            patientCriticalDescription.setId(getUUID());
            patientCriticalDescription.setCreateTime(new Date());
            patientCriticalDescription.setCriticalDescription(criticalObsInfo.getCriticalDescription());
            //criticalDescription危急值内容      CriticalDescription  危急值詳情
            patientCriticalDescription.setPatientId(patient.getId());   //患者id   主键id
            patientCriticalDescription.setVisitNumber(patient.getVisitId());  //患者的住院号     住院号
            patientCriticalDescription.setStatus(1);
            isRepetition = false;
        }
        patientCriticalDescription.setDataTime(dataTime);
        patientCriticalDescription.setReportNumber(criticalObsInfo.getCriticalId());//reportNumber
        if (isRepetition) {//危急值 如果重复 update
            patientCriticalDescriptionService.update(patientCriticalDescription);//危急值
        } else {// 危急值 不重复 insert
            patientCriticalDescriptionService.insert(patientCriticalDescription);
        }
         //危急值实时记录
        // 判断  Status:1正常  -1删除   Flag 0出科 1在科
        if (patient.getStatus()==1 && patient.getFlag()==1){
            String criticalDescription = patientCriticalDescription.getCriticalDescription();
            if(StringUtils.isNotBlank(criticalDescription)){
                if(StringUtils.contains(criticalDescription,"，")){
                    criticalDescription = criticalDescription.replaceAll("，", ",");
                }
                String[] split = criticalDescription.split(",");
                if(split.length == 11){
                    String[] join = {split[3],split[6],split[8],split[9],split[10]};
                    criticalDescription = Joiner.on(",").join(join);
                }
            }

            //创建对象urseRecordForm
            NurseRecordForm nurseRecordForm = new NurseRecordForm();
            nurseRecordForm.setPatientId(patient.getId());//病人id
            nurseRecordForm.setVisitId(patient.getVisitId());//住院号
            nurseRecordForm.setVisitCode(patient.getVisitCode());//本次住院号
            nurseRecordForm.setCreateTime(new Date());
            nurseRecordForm.setId(UUIDUtil.getUUID());
            nurseRecordForm.setDataTime(dataTime);
            nurseRecordForm.setStatus(1);
            nurseRecordForm.setResult(criticalDescription);//获取危急值内容 set->相应异常变化的处理及结果
            /**
             * 添加保存生命体征和护理延续的数据
             */
            try {
                nurseRecordFormService.setNewNurseRecordFormData(nurseRecordForm, null, 1);
            }catch (Exception e){
                 logger.error(e.getMessage());
            }
            //保存到 护理单(三表)
            nurseRecordFormService.insert(nurseRecordForm);
        }
    }
}
